﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Serialization
{
    /// <summary>
    /// 
    /// </summary>
    public class SerializeHelper
    {
        #region 二进制格式序列化

        /// <summary>
        /// 二进制格式将对象或整个连接对象图形序列化。
        /// </summary>
        /// <param name="obj"> 可序列化的对象(对象必须标记为 [Serializable] ) </param>
        /// <returns></returns>
        public static byte[] BinarySerialize(object obj)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(stream, obj);
                return stream.ToArray();
            }
        }

        /// <summary>
        /// 以二进制格式将对象或整个连接对象图形反序列化。
        /// </summary>
        /// <param name="buffer">  </param>
        /// <returns> 返回一个已序列化的对象 </returns>
        public static object BinaryDeserialize(byte[] buffer)
        {
            using (System.IO.Stream stream = new System.IO.MemoryStream(buffer))
            {
                return new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Deserialize(stream);
            }
        }

        #endregion

        #region XML序列化

        /// <summary>
        /// 将对象序列化到 XML 文档中。
        /// </summary>
        /// <param name="obj"> 可序列化的对象 </param>
        /// <returns></returns>
        public static byte[] XmlSerialize(object obj)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                new System.Xml.Serialization.XmlSerializer(obj.GetType()).Serialize(stream, obj);
                return stream.ToArray();
            }
        }

        /// <summary>
        /// 从 XML 文档中反序列化对象。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static object XmlDeserialize<T>(byte[] buffer)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                object value = new System.Xml.Serialization.XmlSerializer(typeof(T)).Deserialize(stream);
                return value != null ? (T)value : default(T);
            }
        }

        #endregion
    }
}
